package solution._0030._0036;

import java.util.ArrayList;
import java.util.HashSet;

/**
 * Created by chen_snow
 * Date: 2021/5/26 20:34
 * Description: 有效的数独
 */
public class Solution {
    public boolean isValidSudoku(char[][] board) {

        ArrayList<HashSet<Integer>> rowList = new ArrayList<>();
        ArrayList<HashSet<Integer>> columnList = new ArrayList<>();
        ArrayList<HashSet<Integer>> boxList = new ArrayList<>();

        for (int i = 0; i < 9; i++) {
            rowList.add(new HashSet<Integer>());
            columnList.add(new HashSet<Integer>());
            boxList.add(new HashSet<Integer>());
        }

        for (int row = 0; row < 9; row++) {
            for (int column = 0; column < 9; column++) {
                if (board[row][column] != '.') {
                    int index = row / 3 * 3 + column / 3;
                    int num = board[row][column] - '0';
                    if (!(checkAndAdd(rowList.get(row), num)
                            && checkAndAdd(columnList.get(column), num)
                            && checkAndAdd(boxList.get(index), num))) {
                        return false;
                    }
                }

            }
        }
        return true;
    }

    public boolean checkAndAdd(HashSet<Integer> data, Integer num) {
        if (data.contains(num)) {
            return false;
        }

        data.add(num);
        return true;
    }
}
